
#include "timer.h"
#include "luas.h"

static void on_lua_timer(const int fd, const short which, void *arg)
{    
    TimerHandler *handler = (TimerHandler *)arg;
    Timer_LUA *hand_data = (Timer_LUA*)handler->hand_data;
    
    js_sys("module", "on_lua_timer %s msgid:%d\n", hand_data->callback, handler->msgid);

    int ir = luas_classfunc(hand_data->self, hand_data->callback, "(%d)",
        handler->msgid);
    if(ir == 1)
    { 
        evtimer_add(&(hand_data->evt), &(hand_data->tv));
    }else{
        //TODO, unref timer
       // luaL_unref(
    }
} 


int timer_add(int self, const char* funcname, int msec, int msgid)
{
    TimerHandler *handler = (TimerHandler *)malloc(sizeof(TimerHandler)+sizeof(Timer_LUA));

    handler->hand_type = TIMER_LUA;    
    
    handler->msgid = msgid;    
    Timer_LUA *hand_data = (Timer_LUA*)handler->hand_data;
    
    int sec = msec / 1000;
    int usec = (msec % 1000) * 1000;
    
    hand_data->tv.tv_sec  = sec;
    hand_data->tv.tv_usec = usec;
    hand_data->self = self;
    strcpy(hand_data->callback, funcname);
    
    evtimer_set(&(hand_data->evt), on_lua_timer, handler);
    evtimer_add(&(hand_data->evt), &(hand_data->tv));
    js_sys("module", "timer_add msgid:%d msec:%d funcname:%s\n", msgid, msec,  funcname);
    
    return 1;
}

 



static int AddTimer(lua_State *L)
{

    if (LUA_ARGNUM == 4 
    && LUA_ISSTRING(3)&& LUA_ISNUMBER(1) && LUA_ISNUMBER(2))
    {
        int msec                = (int)LUA_TONUMBER(1);
        int msgid               = (int)LUA_TONUMBER(2);
        const char *funcname    = (const char *)LUA_TOSTRING(3);
        int self                = (int)luaL_ref(L, LUA_REGISTRYINDEX); 
        
        js_sys("module", "timer_add self:%d, msgid:%d msec:%d funcname:%s\n", self, msgid, msec,  funcname);
        int rt = timer_add(self, funcname, msec, msgid);

        LUA_RETURN(rt);
    }

    LUA_RETURN(0);
}


static luaL_Reg lua_lib[] = 
{
    LUA_FUNC_INIT(AddTimer),
    {NULL, NULL}
};

int timer_init()
{
    luas_reg_lib("Timer", lua_lib);
}
